package servlet.user;

import bean.pojo.User;
import commons.baseServlet.BaseServlet_req_res;
import commons.file.FileUtils;
import commons.r.Write;
import service.UsersService;
import service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * servlet.user
 * User: 坚持
 * Date: 2024/12/24 11:07
 * motto: 树欲静而风不止
 * Description:
 * Version: V1.0
 */
@MultipartConfig
@WebServlet(name = "AvatarUpload",value = "/upload/uploadAvatar")
public class AvatarUpload extends BaseServlet_req_res {
    public void uploadAvatar(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = req.getHeader("X-Token");

        User user = (User) req.getServletContext().getAttribute(token);

        String realPath = req.getServletContext().getRealPath("/img/avatar");
        File avatar = new File(realPath);
        if (!avatar.exists()){
            avatar.mkdirs();
        }


        Part file = req.getPart("file");
        String submittedFileName = file.getSubmittedFileName();
        String suffix = FileUtils.getSuffix(submittedFileName);

        long maxFileSize = 1024 * 1024 * 5; // 最大5MB
        if (file.getSize() > maxFileSize) {
            Write.writeFail(resp, "文件大小超过限制");
            return;
        }
        if (!suffix.matches(".*(jpg|jpeg|png|gif)$")) {
            Write.writeFail(resp, "只能上传图片文件");
            return;
        }
        String newName = (UUID.randomUUID().toString().replaceAll("-","") + suffix);
        String newPath = realPath +"/" + newName;
        String ServerPath = "http://127.0.0.1:8080/img/avatar/" + newName;

        UsersService usersService = new UsersServiceImpl();
        boolean isSuccess = usersService.updateAvatar(user.getUserId(), ServerPath);

        if (isSuccess) {
            file.write(newPath);
            Write.writeSuccess(resp, null, "上传成功");
        }
        else{
            Write.writeFail(resp,"上传失败");
        }
    }
}
